<?php

declare(strict_types=1);

namespace app\model;

use api\channel\jutuike\AroundUnion;
use app\common\service\around\JtkAroundService;
use app\model\base\BaseJtkLocationModel;
use think\facade\Db;

/**
 *
 *
 * @mixin \think\Model
 * @property int $id
 * @property string $city 站点名称
 * @property string $cityCode 城市编码
 * @property int $pid 父ID
 * @property string $firstWord 首字母
 * @property int $jtk_id 聚推客站点id
 * @property int $jtk_pid 聚推客父ID
 * @property string $city_code 城市编码
 * @property string $first_word 首字母
 */
class JtkLocation extends BaseJtkLocationModel
{
    /**
     * 站点数据
     * @return array
     */
    public static function locationAll() {
        $dataList = JtkLocation::query()->group('first_word, id')->order('first_word asc')->select();

        /**
         * 目前数据pid都为0 不需要树形结构
        $tree = [];  // 格式化好的数组
        $dataIdTemp = $dataList ? array_column($dataList, null, 'jtk_id') : [];
        foreach ($dataList as $item) {
            $id = $item['jtk_id'];
            $item['jtk_pid'] != 0 ? $dataIdTemp[$item['jtk_pid']]['children'][] = &$dataIdTemp[$id] : $tree[] = &$dataIdTemp[$id];
        }
        return $tree;
         *
         *  */
        return $dataList;
    }

    /**
     * 根据城市名称获取站点ID 最多不超过5个 => 聚推客 locationIdList 不生效 暂时只取一个
     *
     * @param $cityName
     * @return array
     */
    public static function locationIdByCityName($cityName) {
        // 聚推客站点id列表，最多支持5个站点
//        $locationIdAttr = JtkLocation::query()->whereLike('city', '%' . $cityName . '%')->limit(1)->column('jtk_id');
        $locationModel = JtkLocation::query()->whereLike('city', '%' . $cityName . '%')->find();
        return $locationModel->jtk_id ?? 0;
    }

    /**
     * 保存聚推客所有站点数据
     * @return bool
     * @throws \think\db\exception\DbException
     */
    public static function saveLocationData() {
        // 聚推客获取所有站点信息
        $aroundUnion =  new AroundUnion();
        $res = $aroundUnion->getLocationList();
        if (isset($res['code']) && $res['code'] == JtkAroundService::CODE_FAIL) {
            echo '聚推客所有站点信息错误-' . $res['msg'] . PHP_EOL;
            return false;
        }
        $dataList = $res['data'];
        $saveData = [];
        foreach ($dataList as $item) {
            $saveData[] = [
                'jtk_id' => $item['id'],
                'jtk_pid' => $item['pid'],
                'city' => $item['city'],
                'city_code' => $item['cityCode'] ?? '',
                'first_word' => $item['firstWord'],
            ];

        }
        Db::name(JtkLocation::getTable())->delete(true);
        $model = new JtkLocation();
        $model->saveAll($saveData);
        echo '聚推客所有站点信息保存成功' . PHP_EOL;
        return true;
    }
}
